package com.itgacl.magic4j.libcommon.component.license.crypto;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * 通过AES方式，对文本内容进行加密和解密
 */
public class AESUtils{
	/**
	 * 密钥算法
	 */
	public static final  String ALGORITHM = "AES";
	public static final  String SHA1PRNG  = "SHA1PRNG";
	/**
	 * 密钥长度
	 */
	private static final int    KEY_SIZE  = 128;

	/**
	 * 解密
	 *
	 * @param key 加密密钥
	 * @param txt 待解密内容
	 * @return 解密结果
	 * @throws Exception 密钥错误，无法解密时，会抛出对应的异常
	 */
	public static String decrypt(String key, String txt) throws Exception {
		SecretKey secretKey = new SecretKeySpec(B64Utils.decode(key), ALGORITHM);
		byte[] raw = secretKey.getEncoded();
		SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
		return new String(cipher.doFinal(B64Utils.decode(txt)));
	}

	/**
	 * 加密
	 *
	 * @param key 加密私钥
	 * @param txt 待加密内容
	 * @return 加密结果
	 * @throws Exception 加密异常
	 */
	public static String encrypt(String key, String txt) throws Exception {
		SecretKey secretKey = new SecretKeySpec(B64Utils.decode(key), ALGORITHM);
		byte[] raw = secretKey.getEncoded();
		SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
		return B64Utils.encode(cipher.doFinal(txt.getBytes()));
	}

	/**
	 * 创建私钥
	 *
	 * @param arg 生成私钥的种子
	 * @return 返回私钥
	 * @throws NoSuchAlgorithmException 生成异常
	 */
	public static String genKey(String arg) throws NoSuchAlgorithmException {
		KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
		SecureRandom secureRandom = SecureRandom.getInstance(SHA1PRNG);
		if (arg != null && !"".equals(arg)) {
			secureRandom.setSeed(arg.getBytes());
		}

		keyGenerator.init(KEY_SIZE, secureRandom);
		SecretKey secretKey = keyGenerator.generateKey();
		return B64Utils.encode(secretKey.getEncoded());
	}
}
